package sys.knot.data.access;

import sys.knot.model.ResultPart;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class ResultQueue {
    private BlockingQueue<ResultPart> queue;
    private List<String> warnings = Collections.synchronizedList(new ArrayList<>());
    private List<String> errors = Collections.synchronizedList(new ArrayList<>());

    //activeProducer - keep track of all tasks, and poll them directly? slow?
    private volatile int activeTasks = 0;
    private volatile boolean cancelled = false;

    public ResultQueue(int capacity) {
        queue = new ArrayBlockingQueue<>(capacity);
    }

    public void registerTask(){
        activeTasks++;
    }
    public void unRegisterTask(){
        activeTasks--;
    }
    public boolean isFinishedAndEmpty() {
        return activeTasks == 0 && queue.isEmpty();
    }

    public void cancel() {
        cancelled = true;
    }
    public boolean isCancelled() {
        return cancelled;
    }

    public void put(ResultPart element) throws InterruptedException {
        queue.put(element);
    }
    public ResultPart take() throws InterruptedException {
        return queue.take();
    }
    public ResultPart poll(long timeout, TimeUnit timeUnit) throws InterruptedException {
        return queue.poll(timeout, timeUnit);
    }

    public void addErrorMessage(String message) {
        errors.add(message);
    }

    public void addWarningMessage(String message) {
        warnings.add(message);
    }

    public List<String> getWarnings() {
        return warnings;
    }

    public List<String> getErrors() {
        return errors;
    }
}